package com.woniu.gateway.filter;

import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @author 杜梅杰
 * @description
 * @date 2024/4/29 16:45
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter {

    @Autowired
    private ReactiveStringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取token
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();

        //白名单
        return redisTemplate.opsForHash().hasKey("white", path).flatMap(b -> {
            if (b) {
                //放行
                return chain.filter(exchange);
            }
            String token = request.getHeaders().getFirst("token");

            //如果是空直接返回错误
            if (StringUtils.isEmpty(token)) {
                return getVoidMono(exchange);
            }

            //jwt检测
            boolean verify = false;
            try {
                verify = JWTUtil.verify(token, "woniu".getBytes());
            } catch (Exception e) {
                //e.printStackTrace(); 不要用,会消耗CPU
                log.error("token verify error:{}", e);
                verify = false;
            }

            //再判断token是否有效
            if (!verify) {
                return getVoidMono(exchange);
            }


            //从redis取jwt
            return redisTemplate.hasKey(token).flatMap(c->{
                if (c) {
                    //jwt延期
                    redisTemplate.expire(token, Duration.ofMinutes(30)).subscribe();

                    //放行
                    return chain.filter(exchange);
                }

                return getVoidMono(exchange);
            });

        });

    }


    private static Mono<Void> getVoidMono(ServerWebExchange exchange) {
        log.error("认证失败");
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.FORBIDDEN);

        return response.setComplete();
    }
}
